/**
 * 音频权限管理器
 * 统一处理音频权限请求、状态管理和用户交互界面
 */

export class AudioPermissionManager {
    constructor() {
        this.audioPermissionGranted = false;
        this.isProcessing = false;
        this.audioContext = null;
        this.permissionDialog = null;
        this.eventCallbacks = new Map();
        this.initAudioContext();
    }

    /**
     * 初始化音频上下文
     */
    initAudioContext() {
        try {
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
            console.log('音频上下文初始化成功');
        } catch (error) {
            console.error('音频上下文初始化失败:', error);
        }
    }

    /**
     * 创建音频权限对话框
     */
    createPermissionDialog() {
        if (this.permissionDialog) {
            return this.permissionDialog;
        }

        // 创建对话框容器
        const dialogContainer = document.createElement('div');
        dialogContainer.id = 'audio-permission-dialog';
        dialogContainer.className = 'audio-permission-dialog';
        dialogContainer.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            color: white;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease;
        `;

        // 创建内容区域
        const content = document.createElement('div');
        content.className = 'audio-permission-content';
        content.style.cssText = `
            background: #1a1a1a;
            border-radius: 16px;
            padding: 40px;
            text-align: center;
            max-width: 400px;
            width: 90%;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
        `;

        // 创建图标
        const iconContainer = document.createElement('div');
        iconContainer.style.cssText = `
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: linear-gradient(135deg, #4CAF50, #2196F3);
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto 30px;
        `;

        const icon = document.createElement('span');
        icon.innerHTML = '🔊';
        icon.style.cssText = 'font-size: 60px;';
        iconContainer.appendChild(icon);

        // 创建标题
        const title = document.createElement('h2');
        title.textContent = '启用音频权限';
        title.style.cssText = `
            margin: 0 0 20px;
            font-size: 28px;
            font-weight: 700;
            color: #fff;
        `;

        // 创建描述
        const description = document.createElement('p');
        description.textContent = '需要访问您的麦克风以进行语音对话。请在弹出的提示中允许访问。';
        description.style.cssText = `
            margin: 0 0 30px;
            font-size: 16px;
            line-height: 1.6;
            color: #e0e0e0;
        `;

        // 创建按钮
        const button = document.createElement('button');
        button.textContent = '允许访问麦克风';
        button.className = 'audio-permission-button';
        button.style.cssText = `
            background: linear-gradient(135deg, #4CAF50, #2196F3);
            color: white;
            border: none;
            border-radius: 50px;
            padding: 15px 40px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
        `;

        // 添加按钮悬停效果
        button.addEventListener('mouseenter', () => {
            button.style.transform = 'translateY(-2px)';
            button.style.boxShadow = '0 6px 20px rgba(76, 175, 80, 0.4)';
        });

        button.addEventListener('mouseleave', () => {
            button.style.transform = 'translateY(0)';
            button.style.boxShadow = '0 4px 15px rgba(76, 175, 80, 0.3)';
        });

        // 绑定点击事件
        button.addEventListener('click', () => {
            this.requestAudioPermission();
        });

        // 创建加载状态
        const loadingContainer = document.createElement('div');
        loadingContainer.id = 'audio-permission-loading';
        loadingContainer.style.cssText = `
            display: none;
            flex-direction: column;
            align-items: center;
            gap: 20px;
        `;

        const loadingSpinner = document.createElement('div');
        loadingSpinner.style.cssText = `
            width: 50px;
            height: 50px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-top: 3px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        `;

        const loadingText = document.createElement('p');
        loadingText.textContent = '正在启用音频...';
        loadingText.style.cssText = `
            margin: 0;
            font-size: 16px;
            color: #e0e0e0;
        `;

        loadingContainer.appendChild(loadingSpinner);
        loadingContainer.appendChild(loadingText);

        // 创建错误状态
        const errorContainer = document.createElement('div');
        errorContainer.id = 'audio-permission-error';
        errorContainer.style.cssText = `
            display: none;
            flex-direction: column;
            align-items: center;
            gap: 20px;
        `;

        const errorIcon = document.createElement('span');
        errorIcon.innerHTML = '⚠️';
        errorIcon.style.cssText = 'font-size: 60px;';

        const errorText = document.createElement('p');
        errorText.textContent = '无法获取麦克风权限';
        errorText.style.cssText = `
            margin: 0;
            font-size: 16px;
            color: #ff6b6b;
        `;

        const errorDescription = document.createElement('p');
        errorDescription.textContent = '请检查浏览器权限设置并允许访问麦克风。';
        errorDescription.style.cssText = `
            margin: 0;
            font-size: 14px;
            color: #e0e0e0;
            max-width: 300px;
            text-align: center;
        `;

        const retryButton = document.createElement('button');
        retryButton.textContent = '重试';
        retryButton.style.cssText = `
            background: #ff6b6b;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 10px 30px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s ease;
        `;

        retryButton.addEventListener('click', () => {
            this.requestAudioPermission();
        });

        errorContainer.appendChild(errorIcon);
        errorContainer.appendChild(errorText);
        errorContainer.appendChild(errorDescription);
        errorContainer.appendChild(retryButton);

        // 组装内容
        content.appendChild(iconContainer);
        content.appendChild(title);
        content.appendChild(description);
        content.appendChild(button);
        content.appendChild(loadingContainer);
        content.appendChild(errorContainer);

        dialogContainer.appendChild(content);

        // 添加CSS动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `;
        document.head.appendChild(style);

        document.body.appendChild(dialogContainer);
        this.permissionDialog = dialogContainer;

        return dialogContainer;
    }

    /**
     * 显示权限对话框
     */
    showDialog() {
        const dialog = this.createPermissionDialog();
        dialog.style.opacity = '1';
        dialog.style.visibility = 'visible';
    }

    /**
     * 隐藏权限对话框
     */
    hideDialog() {
        if (this.permissionDialog) {
            this.permissionDialog.style.opacity = '0';
            this.permissionDialog.style.visibility = 'hidden';
            
            // 重置状态
            this.hideLoading();
            this.hideError();
        }
    }

    /**
     * 显示加载状态
     */
    showLoading() {
        const dialog = this.permissionDialog;
        if (dialog) {
            dialog.querySelector('.audio-permission-content').style.display = 'none';
            dialog.querySelector('#audio-permission-loading').style.display = 'flex';
            dialog.querySelector('#audio-permission-error').style.display = 'none';
        }
    }

    /**
     * 隐藏加载状态
     */
    hideLoading() {
        const dialog = this.permissionDialog;
        if (dialog) {
            dialog.querySelector('#audio-permission-loading').style.display = 'none';
        }
    }

    /**
     * 显示错误状态
     */
    showError(message = null) {
        const dialog = this.permissionDialog;
        if (dialog) {
            dialog.querySelector('.audio-permission-content').style.display = 'none';
            dialog.querySelector('#audio-permission-loading').style.display = 'none';
            dialog.querySelector('#audio-permission-error').style.display = 'flex';
            
            if (message) {
                dialog.querySelector('#audio-permission-error p:first-of-type').textContent = message;
            }
        }
    }

    /**
     * 隐藏错误状态
     */
    hideError() {
        const dialog = this.permissionDialog;
        if (dialog) {
            dialog.querySelector('#audio-permission-error').style.display = 'none';
        }
    }

    /**
     * 请求音频权限
     */
    async requestAudioPermission() {
        if (this.isProcessing) {
            return;
        }

        this.isProcessing = true;
        this.showLoading();

        try {
            console.log('请求音频权限...');
            
            // 请求麦克风权限
            const stream = await navigator.mediaDevices.getUserMedia({
                audio: {
                    echoCancellation: true,
                    noiseSuppression: true,
                    autoGainControl: true
                }
            });

            // 停止流，但保留权限
            stream.getTracks().forEach(track => track.stop());

            // 确保音频上下文处于活动状态
            if (this.audioContext) {
                if (this.audioContext.state === 'suspended') {
                    await this.audioContext.resume();
                }
            }

            this.audioPermissionGranted = true;
            console.log('音频权限已授予');
            
            // 通知权限授予
            this.notifyPermissionGranted();
            
            // 隐藏对话框
            this.hideDialog();
            
        } catch (error) {
            console.error('音频权限请求失败:', error);
            
            // 显示错误状态
            this.showError('无法获取麦克风权限');
            
            // 通知权限错误
            this.notifyPermissionError(error);
            
        } finally {
            this.isProcessing = false;
        }
    }

    /**
     * 检查权限状态
     */
    async checkPermissionStatus() {
        try {
            // 检查媒体设备权限状态
            if (navigator.permissions && navigator.permissions.query) {
                const permission = await navigator.permissions.query({ name: 'microphone' });
                return permission.state === 'granted';
            }
            
            // 回退到检查audioPermissionGranted标志
            return this.audioPermissionGranted;
        } catch (error) {
            console.warn('检查权限状态失败:', error);
            return false;
        }
    }

    /**
     * 确保音频上下文正在运行
     */
    async ensureAudioContextRunning() {
        try {
            if (!this.audioContext) {
                this.initAudioContext();
            }
            
            if (this.audioContext.state === 'suspended') {
                await this.audioContext.resume();
                console.log('音频上下文已恢复');
            }
            
            return true;
        } catch (error) {
            console.error('确保音频上下文运行失败:', error);
            return false;
        }
    }

    /**
     * 获取音频上下文
     */
    getAudioContext() {
        return this.audioContext;
    }

    /**
     * 添加事件监听器
     */
    on(event, callback) {
        if (!this.eventCallbacks.has(event)) {
            this.eventCallbacks.set(event, []);
        }
        this.eventCallbacks.get(event).push(callback);
    }

    /**
     * 移除事件监听器
     */
    off(event, callback) {
        if (this.eventCallbacks.has(event)) {
            const callbacks = this.eventCallbacks.get(event);
            const index = callbacks.indexOf(callback);
            if (index > -1) {
                callbacks.splice(index, 1);
            }
        }
    }

    /**
     * 触发事件
     */
    emit(event, data = null) {
        if (this.eventCallbacks.has(event)) {
            const callbacks = this.eventCallbacks.get(event);
            callbacks.forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`触发事件 ${event} 时出错:`, error);
                }
            });
        }
    }

    /**
     * 通知权限授予
     */
    notifyPermissionGranted() {
        this.emit('permissionGranted');
    }

    /**
     * 通知权限拒绝
     */
    notifyPermissionDenied() {
        this.emit('permissionDenied');
    }

    /**
     * 通知权限错误
     */
    notifyPermissionError(error) {
        this.emit('permissionError', { error });
    }
}